package games.tankwars.behaviors;

import java.util.Set;

import games.tankwars.Level;
import games.tankwars.Level;
import games.tankwars.entities.Bullet;
import games.tankwars.entities.MazeElement;
import vooga.behaviors.MoveBehavior;
import vooga.core.AbstractLevel;
import vooga.entities.Entity;
import vooga.geom.DoubleDimension;
import vooga.geom.Vector;

public class TankAI extends vooga.behaviors.AbstractBehavior
{
    private games.tankwars.entities.Tank myTank;
    private vooga.core.AbstractLevel myLevel;
    private int myTimer;
    private boolean onTail;
        
    public TankAI (games.tankwars.entities.Tank tank, Level level)
    {
    	myTimer=0;
        myTank = tank;
        myLevel=level;
        onTail=false;
    }

    
    public TankAI (games.tankwars.entities.Tank tank, AbstractLevel level)
    {
    	myTimer=0;
        myTank = tank;
        myLevel=level;
        onTail=false;
    }
	@Override
	public void step(Entity target) {
		myTimer++;
		double BULLET_MOVE_SPEED=5;
		
		double dx=myTank.getCenter().getX()-target.getCenter().getX();
		double dy=myTank.getCenter().getY()-target.getCenter().getY();
		double dDistance=Math.sqrt(dx*dx+dy*dy);	
		
		vooga.geom.Vector Velocity = new vooga.geom.Vector();
		
		// TODO Auto-generated method stub
		
		if ((myTank.getCenterX()>target.getCenterX()-20 && myTank.getCenterX()<target.getCenterX()+20) || (myTank.getCenterY()>target.getCenterY()-20 && myTank.getCenterY()<target.getCenterY()+20))
			onTail=true;
		
		if (myTimer%myLevel.getFrameRate()*1 == 0)
		{
			if (dDistance<250 && myTank.isVisible() && onTail)
			{
				Bullet newBullet = new games.tankwars.entities.Bullet((java.awt.geom.Point2D.Double)(target.getCenter().clone()));
				newBullet.setVelocity(new Vector(target.getHeading(),BULLET_MOVE_SPEED));
				newBullet.addBehavior(new MoveBehavior());
				newBullet.addBehavior (new IntersectAndRemoveBoth(Velocity, myTank,myLevel));
				newBullet.addBehavior (new IntersectAndRemove(Velocity, myLevel.getEntities("maze"),myLevel));
				myLevel.addEntity(newBullet);
			}
		}
	}
}
